import datetime
import hashlib
import logging
import os

from django.conf import settings

from main import _script_head  # noqa
from main.common.db_utils import ensure_connection_exist
from main.common.djqscsv import write_csv, write_csv_v2  # add field_setter_map

EXPORT_ROOT_DIR = getattr(settings, 'EXPORT_ROOT_DIR')
EXPORT_URL = getattr(settings, 'EXPORT_URL')
API_ROOT_URL = getattr(settings, 'API_ROOT_URL')
if not os.path.exists(EXPORT_ROOT_DIR):
    os.makedirs(EXPORT_ROOT_DIR)

logger = logging.getLogger('django')


def make_csv_file(name='export_user_exam_', qsv=None, field_header_map=None,
                  field_serializer_map=None, field_setter_map=None):
    ensure_connection_exist()

    now_str = datetime.datetime.now().strftime('%y%m%d%H%M%S')
    filename = name + hashlib.md5(now_str.encode('utf-8')).hexdigest() + now_str + '.csv'
    file_path = EXPORT_ROOT_DIR + filename
    file_url = API_ROOT_URL + EXPORT_URL + filename

    with open(file_path, 'wb') as csv_file:
        write_csv(
            qsv,
            csv_file,
            field_header_map=field_header_map,
            field_serializer_map=field_serializer_map,
            field_setter_map=field_setter_map,
        )
    return file_path, file_url


def make_csv_file_v2(name='export_user_exam_', qsv=None, field_header_map=None,
                     field_serializer_map=None, field_setter_map=None):
    ensure_connection_exist()

    now_str = datetime.datetime.now().strftime('%y%m%d%H%M%S')
    filename = name + hashlib.md5(now_str.encode('utf-8')).hexdigest() + now_str + '.csv'
    file_path = EXPORT_ROOT_DIR + filename
    file_url = API_ROOT_URL + EXPORT_URL + filename

    with open(file_path, 'wb') as csv_file:
        write_csv_v2(
            qsv,
            csv_file,
            field_header_map=field_header_map,
            field_serializer_map=field_serializer_map,
            field_setter_map=field_setter_map,
        )
    return file_path, file_url
